package common;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 文件描述
 *
 * @Author 冯根源
 * @create 2020/4/2 11:23
 */
public class JdbcUtils {
    static Properties properties = null;

    static {
        //加载配置文件
        InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
        properties = new Properties();
        try {
            properties.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        try {
            //加载类驱动
            Class.forName(properties.getProperty("driverClassName"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {

        return DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
    }

    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        System.out.println(getConnection());
    }

    public static void close(Connection connection, PreparedStatement stm) {
        try {
            if (stm != null) stm.close();
            if (connection != null) connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static void close(Connection connection, PreparedStatement stm, ResultSet set) {
        try {
            if (set != null) set.close();
            if (stm != null) stm.close();
            if (connection != null) connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
